"use strict"
const fs = require('fs');


exports.download = function () {
    let id = this.get("id")
    if(!id){
        return this.error("id empty")
    }
    let root = this.config.get("root")
    let path = [root,'xcode',id+'.xcode'].join('/')
    this.res.download(path)
}



exports.create = function () {
    this.output = "json";
    let id = this.get('id');
    if ( !id ) {
        return this.error('id empty');
    }

    let branch = this.branch._id;
    let lock = this.model("lock",branch,"excode",30)
    lock.start("expage",(err,ret)=>{
        if(err){
            return this.error(err,ret)
        }
        else if(ret.length > 0){
            return this.error("服务器正在生成兑换码，请等待30秒后再生成")
        }
        let expage = this.model("expage",branch)
        expage.get(id,null,(e1,r1)=>{
            if(e1){
                return this.error(e1,r1)
            }
            if(r1["status"]>0){
                return this.error("已经生成，请直接下载")
            }
            createCode.call(this,branch,r1,(e2,r2)=>{
                lock.clear();
                if(e2){
                    return this.error(r2[0][0],r2[0][1])
                }
                else{
                    expage.set(id,"status",2,this.callback)
                }
            })
        })
    })
}

function createCode(branch,expage,callback) {
    let root = this.config.get("root")
    let path = [root,'xcode',expage["_id"]+'.xcode'].join('/')

    this.fd = fs.openSync(path,'a+');

    this.seed    = 100;
    this.extime  = parseInt( Date.now() / 1000 );
    this.expage  = expage;
    this.excode  = this.model('excode',branch);
    let task = this.library('task',expage["num"],createCodeTaskWork.bind(this),(e,r)=>{
        fs.close(this.fd,function(){});
        callback(e,r);
    });
    task.start();
}

function createCodeTaskWork(num,callback){
    let roll = this.library("random/Roll",1,9)
    let code = parseInt([roll,this.extime,this.seed + num].join("")).toString(36);
    let data = {"_id": code, "use": 0, "cid": this.expage["cid"],"pid":this.expage["_id"]};
    this.excode.insert(data,  (err, ret)=> {
        if (!err) {
            fs.appendFile(this.fd,code+"\r\n",function(){
                callback(null,code);
            });
        }
        else{
            callback(null,code);
        }
    });
}
